package cn.cas.mango.util.string;

import org.apache.logging.log4j.util.Strings;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;

public class StringUtils {
  public static String preprocessString(String prepareString) {
    return prepareString.replaceAll("“", "\"")
        .replaceAll("”", "\"")
        .replaceAll("（", "(")
        .replaceAll("）", ")");
  }

  public static int countChar(String str, char ch) {
    return (int) str.chars().filter(c -> c == ch).count();
  }

  public static String strip(String str) {
    if (str == null) {
      return null;
    }
    // 使用正则表达式去除Unicode空白字符
    return str.replaceAll("^\\p{Zs}+|\\p{Zs}+$", "");
  }

  public static boolean containsAny(String source, String target) {
    if (source == null || target == null) {
      return false;
    }

    return target.chars().anyMatch(c -> source.indexOf(c) >= 0);
  }

  public static String getUUID() {
    SecureRandom secureRandom = new SecureRandom();
    byte[] seed = secureRandom.generateSeed(16);
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e);
    }
    md5.update(seed);
    UUID uuid = UUID.nameUUIDFromBytes(md5.digest());
    String ret = uuid.toString();
    return ret.substring(0, Math.min(ret.length(), 8));
  }

  public static boolean isChineseOrDigit(char c) {
    // 判断是否是中文字符
    if (c >= 0x4E00 && c <= 0x9FFF) {
      return true;
    }
    // 判断是否是数字
    if (c >= '0' && c <= '9') {
      return true;
    }
    return false;
  }

  private static boolean judgeJapanese(String text) {
    for (char c: text.toCharArray()) {
      // 判断是否是平假名字符
      if (c >= 0x3040 && c <= 0x309F) {
        return true;
      }
      // 判断是否是片假名字符
      if (c >= 0x30A0 && c <= 0x30FF) {
        return true;
      }
    }
    return false;
  }

  public static boolean judgeChinese(String text, double ratio) {
    if (Strings.isBlank(text)) return true;
    if (judgeJapanese(text)) return false;
    int len = text.length();
    int count = 0;
    for (char c: text.toCharArray()) {
      if (isChineseOrDigit(c)) {
        count ++;
      }
    }
    return count * 1.0 / len > ratio;
  }

  public static String transTime2Date(String date) {
    date = date.trim();
    String[] s = date.split(" ");
    if (s.length == 1) {
      return date;
    }
    return s[0].trim();
  }
}
